<?php
namespace app\dao;

use Yii;
use yii\base\Object;
use yii\db\Query;
use app\dao\BaseDAO;
use app\enum\EnumOther;
use app\helpers\scmTokenTool;
use app\helpers\Curl;

/**
 * @desc 产品操作类
 * @author liaojianwen
 * @date 2016年11月17日
 */

class ProductDAO extends BaseDAO
{
	/**
	 * @desc 构造函数
	 * @author liaojianwen
	 * @date 2016-11-17
	 */
	public function __construct()
	{
		parent::__construct();
		$this->_table = 'product';
		$this->_pKey ='product_id';
	}
	
	/**
	 * @inheritdoc
	 */
	public static function tableName()
	{
		return '{{%product}}';
	}
	
	/**
	 * 
	 * @desc 入库类单据获取产品信息
	 * @param string $cond
	 * @param [] $pageInfo
	 * @author liaojianwen
	 * @date 2016-11-17
	 */
	public function getProducts($pageInfo, $name)
	{
		$limit = $pageInfo ['pageSize'];
		$offset = ($pageInfo ['page'] - 1) * $limit;
		$selections = "product_id,product_name,product_sn,quantity,unit_name,quantity_unit,price,unit_content";
		$conditions = "p.delete_flag =:flag";
		$params = array (
				':flag' => EnumOther::NO_DELETE,
		);
		
		$query = new Query ();
		$query->select ( $selections )
		->from ("$this->_table p")
		->where ( $conditions, $params );
		//查询条件
		if (! empty ( $name )) {
			$query->andWhere (['like', 'CONCAT(product_name,product_id)', $name]);//andFilterCompare
		}
		$query->leftJoin("unit u","p.quantity_unit = u.unit_id")
			  ->orderBy ( ['p.product_id'=>SORT_ASC]);
		
		$result ['count'] = $query->count ();
		//查询条件
		$result ['list'] = $query->offset ( $offset )->limit ( $limit )->all ();
		foreach ($result['list'] as &$list){
			$res_unit = ProductUnitDAO::getInstance()->getUnits($list['product_id']);
			$list['product_unit'] = $res_unit;
		}
		
		$result ['page'] = array (
				'page' => $pageInfo ['page'],
				'pageSize' => $pageInfo ['pageSize'] 
		);
		return $result;
	}
	
	
	/**
	 * @desc 获取商品列表
	 * @author liaojianwen
	 * @date 2016-12-07
	 */
	public function getProductList ( $pageInfo, $cond )
	{
		$limit = $pageInfo ['pageSize'];
		$offset = ($pageInfo ['page'] - 1) * $limit;
		$selections = "product_id,product_name,product_sn,quantity,warn_quantity,unit_name,quantity_unit,category_name,unit_content,
				supplier_name,produced_time,quality_time,warn_quantity,(cast(quantity as signed) - cast(warn_quantity as signed)) as ii";
		$conditions = "p.delete_flag =:flag";
		$params = array (
				':flag' => EnumOther::NO_DELETE,
		);
		
		$query = new Query ();
		$query->select ( $selections )
		->from ("$this->_table p")
		->where ( $conditions, $params );
		//查询条件
		if (! empty ( $cond )) {
			if(isset($cond['product_name']) && !empty($cond['product_name'])){
				$query->andWhere (['like', 'p.product_name', $cond['product_name']]);
			}
// 			if(isset($cond['category_id']) && !empty($cond['category_id'])){
// 				$query->andWhere("p.category_id =:catid",[':catid'=>$cond['category_id']]);
// 			}
			if(isset($cond['supplier_id']) && !empty($cond['supplier_id'])){
				$query->andWhere("p.supplier_id =:supid",[':supid'=>$cond['supplier_id']]);
			}
// 			$query->andWhere (['like', 'product_name', $name]);//andFilterCompare
		}
		$query->leftJoin("unit u","p.quantity_unit = u.unit_id")
		->leftJoin("category c","c.category_id = p.category_id")
		->leftJoin("supplier s","s.supplier_id = p.supplier_id");
		
		
		$query->orderBy(['ii'=>SORT_ASC,'p.create_time'=>SORT_DESC]);
		
		if(isset($cond['category_id']) && !empty($cond['category_id'])){
			$res_child = (new Query())->select('category_id')->from('category')->where(['or',['category_id'=>$cond['category_id']],['parent_id'=>$cond['category_id']]])->all();
			$categorys = '';
			foreach ($res_child as $child){
				$categorys .= $child['category_id'] .',';
			}
			$categorys = substr($categorys,0,-1);
			$cates = explode(',', $categorys);
			$query->andWhere(['c.category_id'=>$cates]);
		}
		$result ['count'] = $query->count ();
		//查询条件
		$result ['list'] = $query->offset ( $offset )->limit ( $limit )->all ();
		
		$now = time();
		foreach($result['list'] as &$product){
			$produced_time = $product['produced_time'];
			$quality_time = $product['quality_time'];
			$product['produced_time'] = $produced_time ? date('Y-m-d', $produced_time) : '';
			if ($produced_time &&  $quality_time && $produced_time<$quality_time && (($quality_time - $produced_time) > ($quality_time - $now)*3))
			{
				$product['produced_time'] = '<font color="red" title="'.(($quality_time < $now) ? '商品已过期' : '商品已过2/3保质期').'">'.$product['produced_time'].'</font>';
			}
// 			$res_units = ProductUnitDAO::getInstance()->getUnits($product['product_id']);
// 			$pre_unit = '';
// 			$units_content = '';
// 			foreach($res_units as $key => $unit){
// 				if($key == 0){
// 					$pre_unit = $unit['rate'];
// 					$units_content .= '1'. $unit['unit_name'].'=';
// 				} else {
// 					$units_content .= $pre_unit/$unit['rate'] . $unit['unit_name'] .'=';
// 				}
// 			}
			// $units_content = substr($units_content, 0,strlen($units_content) - 1 );
			// $product['unit_content'] = $units_content;
		}
			
		$result ['page'] = array (
				'page' => $pageInfo ['page'],
				'pageSize' => $pageInfo ['pageSize']
		);
		return $result;
	}
	
	/**
	 * @desc 根据id 获取
	 * @author liaojianwen
	 */
	public function getProductEdit($id)
	{
		$selects = "product_id,product_name,product_sn,quantity_unit,category_id,supplier_id,warn_quantity,description,product_img,
				price,warehouse_id,supply_price,guide_price,barcode,produced_time,quality_time,good_id,sync_store,sync_shop";
		$conditions = "product_id = :id";
		$params =[
			':id'=>$id,
		];
		$query = new Query();
		$result = $query->select($selects)
			->from("$this->_table p")
			->where($conditions,$params)
			->one();
		$result['img'] = $query->select('origin_img,image_id')
								->from('product_image')
								->where("delete_flag=:flag and product_id=:id",[':flag'=>EnumOther::NO_DELETE,':id'=>$id])
								->all();
		return $result;		
	}
	
	/**
	 * @desc 获取库存信息
	 * @param $cond 查询条件
	 * @param $pageInfo 页面信息
	 * @author liaojianwen
	 * @date 2016-12-22
	 */
	public function getStockPile($cond, $filter,$pageInfo)
	{
		$limit = $pageInfo ['pageSize'];
		$offset = ($pageInfo ['page'] - 1) * $limit;
		$selects = "product_id,product_name,product_sn,p.quantity,p.supplier_id,p.quantity_unit,p.genexpectstart_qty,
				p.price,p.amount,p.genexpectstart_amount,c.category_name,unit_name";
		
		
		$conditions = "p.delete_flag = :flag";
		$params  =[
				':flag'=>EnumOther::NO_DELETE,
		];
// 		if(isset($cond['vendor']) && !empty($cond['vendor'])){
// 			$conditions .=" and t.vendor_id =:vid";
// 			$params[':vid'] =$cond['vendor'];
// 		}
		switch ($filter){
			case 0 :
				break;
			case 1:
				$conditions .=" and p.quantity = :qty";
				$params[':qty'] = 0;
				break;
			case 2:
				$conditions .=" and p.quantity <> :qty";
				$params[':qty'] = 0;
				break;
		}
		
		$query = new Query();
		$query->select($selects)
		->from("$this->_table p")
		->leftJoin("category c","c.category_id= p.category_id")
		->leftJoin("unit u","u.unit_id= p.quantity_unit")
		->where($conditions, $params)
		->orderBy ( ['p.create_time'=>SORT_ASC]);
		
		if(isset($cond['name']) && !empty($cond['name'])){
			$query->andwhere(['like','p.product_name', $cond['name']]);
		}
		
		if(isset($cond['category']) && !empty($cond['category'])){
			$res_child = (new Query())->select('category_id')->from('category')->where(['or',['category_id'=>$cond['category']],['parent_id'=>$cond['category']]])->all();
			$categorys = '';
			foreach ($res_child as $child){
				$categorys .= $child['category_id'] .',';
			}
			$categorys = substr($categorys,0,-1);
			$cates = explode(',', $categorys);
			$query->andWhere(['c.category_id'=>$cates]);
		}
		$result ['count'] = $query->count ();
		$result ['list'] = $query->offset ( $offset )->limit ( $limit )->all ();
		$result ['page'] = array (
				'page' => $pageInfo ['page'],
				'pageSize' => $pageInfo ['pageSize']
		);
		return $result;
		
	}
	
	/**
	 * @desc 获取库存导出信息
	 * @author liaojianwen
	 * @date 2017-03-13
	 */
	public function getProductStock($cond)
	{
		$selects = "product_id,product_name,product_sn,p.quantity,p.supplier_id,p.quantity_unit,p.genexpectstart_qty,
				p.price,p.amount,p.genexpectstart_amount,c.category_name,unit_name,s.supplier_name";
		$conditions = "p.delete_flag = :flag";
		$params  =[
				':flag'=>EnumOther::NO_DELETE,
		];
		
		$filter = isset($cond['filter']) ? $cond['filter'] : 0;
		switch ($filter){
			case 0 :
				break;
			case 1:
				$conditions .=" and p.quantity = :qty";
				$params[':qty'] = 0;
				break;
			case 2:
				$conditions .=" and p.quantity <> :qty";
				$params[':qty'] = 0;
				break;
		}
		
		$query = new Query();
		$query->select($selects)
		->from("$this->_table p")
		->leftJoin("category c","c.category_id= p.category_id")
		->leftJoin("unit u","u.unit_id= p.quantity_unit")
		->leftJoin("supplier s","s.supplier_id = p.supplier_id")
		->where($conditions, $params)
		->orderBy ( ['p.create_time'=>SORT_ASC]);
// 		->groupBy("`p`.`supplier_id`,`product_id`");
		
		if(isset($cond['name']) && !empty($cond['name'])){
			$query->andwhere(['like','p.product_name', $cond['name']]);
		}
		if(isset($cond['category']) && !empty($cond['category'])){
			$res_child = (new Query())->select('category_id')->from('category')->where(['or',['category_id'=>$cond['category']],['parent_id'=>$cond['category']]])->all();
			$categorys = '';
			foreach ($res_child as $child){
				$categorys .= $child['category_id'] .',';
			}
			$categorys = substr($categorys,0,-1);
			$cates = explode(',', $categorys);
			$query->andWhere(['c.category_id'=>$cates]);
		}
		$result ['count'] = $query->count ();
		$result['list'] = $query->all ();
		return $result;
	}
	
	
	/**
	 * @desc 获取库存导出信息
	 * @author liaojianwen
	 * @date 2017-05-08
	 */
	public function getExplodeProduct($cond)
	{
		$selects = "product_id,product_name,product_sn,p.quantity,p.supplier_id,p.quantity_unit,supply_price,guide_price,
				p.price,p.amount,p.genexpectstart_amount,c.category_name,unit_name,s.supplier_name,unit_content";
		$conditions = "p.delete_flag = :flag";
		$params  =[
				':flag'=>EnumOther::NO_DELETE,
		];
	
		if(isset($cond['category']) && !empty($cond['category'])){
			$conditions .=" and c.category_id =:cate";
			$params[':cate'] = $cond['category'];
		}
		
		if(isset($cond['vendor']) && !empty($cond['vendor'])){
			$conditions .=" and c.supplier_id =:supid";
			$params[':supid'] = $cond['vendor'];
		}
		$query = new Query();
		$query->select($selects)
		->from("$this->_table p")
		->leftJoin("category c","c.category_id= p.category_id")
		->leftJoin("unit u","u.unit_id= p.quantity_unit")
		->leftJoin("supplier s","s.supplier_id = p.supplier_id")
		->where($conditions, $params)
		->orderBy ( ['p.supplier_id'=>SORT_ASC]);
		
	
		if(isset($cond['name']) && !empty($cond['name'])){
			$query->andwhere(['like','p.product_name', $cond['name']]);
		}
		$result ['count'] = $query->count ();
		$result['list'] = $query->all ();
		return $result;
	}
	
    public static function updateAllCounters($counters, $condition = '', $params = [])
    {
		if (isset($counters['quantity']))
		{
			$product_id = isset($params[':id']) ? $params[':id'] : (isset($params[':pid']) ? $params[':pid'] : $params[':product_id']);
			if ($product_id)
			{
				$product = self::getInstance()->iselect(['product_id','product_name','warn_quantity','quantity'], "warn_quantity>0 AND product_id=:id", [':id'=>$product_id], 'one');
				if ($product && $product['quantity'] < $product['warn_quantity'])
				{
					$url = Yii::$app->params ['shopUrl'] .'api/stock.php?act=inventory_warning';
					$url .= "&product_id=".$product['product_id']."&product_name=".urlencode($product['product_name'])."&quantity=".$product['quantity'];
					$key = scmTokenTool::getInstance()->getToken();
					Curl::curlOption($url, 'GET', '', $key);
				}
			}
		}
		
		return parent::updateAllCounters($counters, $condition, $params);
	}
	
    public static function syncStockToShop($product_id, $quantity)
    {
		if ($product_id)
		{
			$product = self::getInstance()->iselect(['quantity','good_id','attr_id'], "product_id=:id", [':id'=>$product_id], 'one');
			if ($product)
			{
				$goods_id = $product['good_id'];
				$goods_attr_id = $product['attr_id'];
				$quantity = $product['quantity'] + $quantity;
				
				$url = Yii::$app->params ['shopUrl'] .'api/stock.php?act=update_quantity';
				$url .= "&product_id=".$product_id."&goods_id=".$goods_id."&goods_attr_id=".$goods_attr_id."&quantity=".$quantity;
				$key = scmTokenTool::getInstance()->getToken();
				return Curl::curlOption($url, 'GET', '', $key);
			}
			return '';
		}
	}
	
	
	/**
	 * @desc 获取商品
	 * @author hehuawei
	 * @date 2017-11-27
	 */
	public function getGoodsData($timeTemp)
	{
		$query = new Query();

		$query->select('product_id,product_name,produced_time,quality_time')->from($this->_table);
	
		//生产期
	    $query->andWhere(['<=','produced_time',$timeTemp]);
	    //保质期
	    $query->andWhere(['>=','quality_time',$timeTemp]);

        $goodsQuantity = $query->all();
		return $goodsQuantity;	
	
	}
}
